import React, { useState } from 'react';
import { Modal, Tabs, Button, Form, Input, Checkbox, Divider, message, Alert } from 'antd';
import { UserOutlined, LockOutlined, MailOutlined, WechatFilled, BellFilled, CloseOutlined, RobotFilled } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { sendCode, loginWithPassword, loginWithCode, register, checkEmail } from './api/auth';

const mainColor = '#5B6DFF';

export default function AuthModal({ open, onClose }) {
  const [mode, setMode] = useState('login');
  const [loginType, setLoginType] = useState('password'); // 'password' 或 'code'
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [countdown, setCountdown] = useState(0);
  const [errorMessage, setErrorMessage] = useState(''); // 添加错误信息状态
  const navigate = useNavigate();

  // 清除错误信息
  const clearError = () => {
    setErrorMessage('');
  };

  // 切换模式时清除错误信息
  const handleModeChange = (newMode) => {
    setMode(newMode);
    clearError();
  };

  // 切换登录类型时清除错误信息
  const handleLoginTypeChange = (newType) => {
    setLoginType(newType);
    clearError();
  };

  // 清除确认密码字段的错误
  const clearConfirmPasswordError = () => {
    form.setFields([
      {
        name: 'confirm',
        errors: []
      }
    ]);
  };

  // 发送验证码
  const sendVerificationCode = async () => {
    try {
      const email = form.getFieldValue('email');
      if (!email) {
        setErrorMessage('请先输入邮箱地址');
        return;
      }
      setLoading(true);
      setErrorMessage(''); // 清除之前的错误信息
      
      // 先检查邮箱状态
      const emailCheck = await checkEmail(email);
      if (!emailCheck.success) {
        setErrorMessage('请输入正确的邮箱格式');
        return;
      }
      
      // 根据模式进行不同的检查
      if (mode === 'login') {
        // 登录模式：检查邮箱是否已注册
        if (!emailCheck.exists) {
          setErrorMessage('该邮箱尚未注册');
          return;
        }
      } else {
        // 注册模式：检查邮箱是否已被注册
        if (emailCheck.exists) {
          setErrorMessage('该邮箱已被注册');
          return;
        }
      }
      
      // 发送验证码
      const data = await sendCode(email);
      if (data.success) {
        message.success('验证码已发送到您的邮箱');
        setCountdown(60);
        const timer = setInterval(() => {
          setCountdown((prev) => {
            if (prev <= 1) {
              clearInterval(timer);
              return 0;
            }
            return prev - 1;
          });
        }, 1000);
      } else {
        // 显示后端返回的错误信息
        setErrorMessage(data.message || '发送验证码失败');
        console.error('发送验证码失败:', data);
      }
    } catch (error) {
      // 处理网络错误
      let errorMsg = '网络错误，请重试';
      
      if (error.response) {
        const responseData = error.response.data;
        errorMsg = responseData.message || `请求失败 (${error.response.status})`;
      } else if (error.message) {
        errorMsg = error.message;
      }
      
      setErrorMessage(errorMsg);
      console.error('发送验证码异常:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      setLoading(true);
      setErrorMessage(''); // 清除之前的错误信息
      
      if (mode === 'register') {
        // 注册模式：先进行前端验证
        // 第一步：检查密码和确认密码是否一致
        if (values.password !== values.confirm) {
          form.setFields([
            {
              name: 'confirm',
              errors: ['两次输入的密码不一致']
            }
          ]);
          setLoading(false);
          return;
        }
        
        // 第二步：检查邮箱是否已被注册
        const emailCheck = await checkEmail(values.email);
        if (!emailCheck.success) {
          setErrorMessage('请输入正确的邮箱格式');
          setLoading(false);
          return;
        }
        if (emailCheck.exists) {
          setErrorMessage('该邮箱已被注册');
          setLoading(false);
          return;
        }
        
        // 第三步：验证码检查（后端会进行验证）
        // 这里可以添加前端验证码格式检查
        if (!values.code || values.code.length !== 6) {
          setErrorMessage('请输入6位验证码');
          setLoading(false);
          return;
        }
      }
      
      let data;
      if (mode === 'login') {
        if (loginType === 'password') {
          data = await loginWithPassword(values.email, values.password);
        } else {
          data = await loginWithCode(values.email, values.code);
        }
      } else {
        data = await register({
          name: values.name,
          email: values.email,
          password: values.password,
          code: values.code
        });
      }
      if (data.success) {
        message.success(mode === 'login' ? '登录成功' : '注册成功');
        localStorage.setItem('token', data.token);
        localStorage.setItem('user', JSON.stringify(data.user));
        navigate('/main/dashboard');
        onClose();
      } else {
        // 显示后端返回的错误信息
        setErrorMessage(data.message || '操作失败，请重试');
        console.error('操作失败:', data);
      }
    } catch (error) {
      // 处理网络错误和验证错误
      let errorMsg = '操作失败，请重试';
      
      if (error.response) {
        const responseData = error.response.data;
        errorMsg = responseData.message || `请求失败 (${error.response.status})`;
      } else if (error.message) {
        errorMsg = error.message;
      }
      
      setErrorMessage(errorMsg);
      console.error('操作异常:', error);
    } finally {
      setLoading(false);
    }
  };

  return (
    <Modal
      open={open}
      footer={null}
      closable={false}
      width={380}
      bodyStyle={{ padding: 0, borderRadius: 12 }}
      style={{ top: 40 }}
      maskClosable={true}
      onCancel={onClose}
    >
      <div style={{ padding: 32, borderRadius: 12, background: '#fff', position: 'relative' }}>
        <Button
          type="text"
          icon={<CloseOutlined style={{ fontSize: 18 }} />}
          onClick={onClose}
          style={{ position: 'absolute', right: 16, top: 16 }}
        />
        <div style={{ textAlign: 'center', marginBottom: 16 }}>
          <RobotFilled style={{ fontSize: 40, color: mainColor, marginBottom: 8 }} />
          <div style={{ fontWeight: 700, fontSize: 22, marginBottom: 4 }}>{mode === 'login' ? '欢迎回来' : '创建账号'}</div>
          <div style={{ color: '#888', fontSize: 14, marginBottom: 8 }}>{mode === 'login' ? '登录你的 AI 面试助手账号' : '快速注册 AI 面试助手'}</div>
        </div>
        
        {mode === 'login' && (
          <div style={{ display: 'flex', gap: 8, marginBottom: 16 }}>
            <Button 
              block 
              type={loginType === 'password' ? 'primary' : 'default'}
              onClick={() => handleLoginTypeChange('password')}
              style={{ 
                background: loginType === 'password' ? mainColor : '#f5f5f5',
                color: loginType === 'password' ? '#fff' : '#333',
                borderColor: loginType === 'password' ? mainColor : '#d9d9d9'
              }}
            >
              密码登录
            </Button>
            <Button 
              block 
              type={loginType === 'code' ? 'primary' : 'default'}
              onClick={() => handleLoginTypeChange('code')}
              style={{ 
                background: loginType === 'code' ? mainColor : '#f5f5f5',
                color: loginType === 'code' ? '#fff' : '#333',
                borderColor: loginType === 'code' ? mainColor : '#d9d9d9'
              }}
            >
              验证码登录
            </Button>
          </div>
        )}
        
        <div style={{ display: 'flex', gap: 8, marginBottom: 16 }}>
          {/* 删除QQ和微信登录/注册按钮 */}
        </div>
        <Divider plain style={{ color: '#aaa', margin: '16px 0' }}>请使用邮箱{mode === 'login' ? '登录' : '注册'}</Divider>
        
        {/* 错误信息显示区域 */}
        {errorMessage && (
          <Alert
            message={errorMessage}
            type="error"
            showIcon
            closable
            onClose={() => setErrorMessage('')}
            style={{ marginBottom: 16 }}
          />
        )}
        
        <Form
          form={form}
          layout="vertical"
          requiredMark={false}
          style={{ marginBottom: 0 }}
          onFinish={handleSubmit}
        >
          {mode === 'register' && (
            <Form.Item name="name" rules={[{ required: true, message: '请输入姓名' }]}
              style={{ marginBottom: 12 }}>
              <Input prefix={<UserOutlined />} placeholder="请输入姓名" size="large" />
            </Form.Item>
          )}
          <Form.Item name="email" rules={[{ required: true, message: '请输入邮箱' }]}
            style={{ marginBottom: 12 }}>
            <Input prefix={<MailOutlined />} placeholder="请输入邮箱" size="large" />
          </Form.Item>
          
          {(mode === 'login' && loginType === 'password') && (
            <Form.Item name="password" rules={[{ required: true, message: '请输入密码' }]}
              style={{ marginBottom: 12 }}>
              <Input.Password prefix={<LockOutlined />} placeholder="请输入密码" size="large" />
            </Form.Item>
          )}
          
          {(mode === 'login' && loginType === 'code') && (
            <Form.Item name="code" rules={[{ required: true, message: '请输入验证码' }]}
              style={{ marginBottom: 12 }}>
              <div style={{ display: 'flex', gap: 8 }}>
                <Input placeholder="请输入验证码" size="large" style={{ flex: 1 }} />
                <Button 
                  size="large" 
                  onClick={sendVerificationCode}
                  disabled={countdown > 0 || loading}
                  style={{ background: mainColor, color: '#fff', borderColor: mainColor }}
                >
                  {countdown > 0 ? `${countdown}s` : '发送验证码'}
                </Button>
              </div>
            </Form.Item>
          )}
          
          {mode === 'register' && (
            <>
              <Form.Item name="password" rules={[
                { required: true, message: '请输入密码' },
                { min: 6, message: '密码长度不能少于6位' }
              ]}
                style={{ marginBottom: 12 }}>
                <Input.Password 
                  prefix={<LockOutlined />} 
                  placeholder="设置登录密码" 
                  size="large"
                  onChange={clearConfirmPasswordError}
                />
              </Form.Item>
              <Form.Item name="confirm" rules={[
                { required: true, message: '请再次输入密码' }
              ]} style={{ marginBottom: 12 }}>
                <Input.Password 
                  prefix={<LockOutlined />} 
                  placeholder="请再次输入密码" 
                  size="large"
                  onChange={clearConfirmPasswordError}
                />
              </Form.Item>
              <Form.Item name="code" rules={[{ required: true, message: '请输入验证码' }]}
                style={{ marginBottom: 12 }}>
                <div style={{ display: 'flex', gap: 8 }}>
                  <Input placeholder="请输入验证码" size="large" style={{ flex: 1 }} />
                  <Button 
                    size="large" 
                    onClick={sendVerificationCode}
                    disabled={countdown > 0 || loading}
                    style={{ background: mainColor, color: '#fff', borderColor: mainColor }}
                  >
                    {countdown > 0 ? `${countdown}s` : '发送验证码'}
                  </Button>
                </div>
              </Form.Item>
            </>
          )}
          
          {mode === 'register' && (
            <Form.Item name="agree" valuePropName="checked" rules={[{ required: true, message: '请同意协议' }]} style={{ marginBottom: 12 }}>
              <Checkbox>
                我已阅读并同意
                <a href="#" style={{ color: mainColor }} target="_blank" rel="noreferrer">服务条款</a>
                和
                <a href="#" style={{ color: mainColor }} target="_blank" rel="noreferrer">隐私政策</a>
              </Checkbox>
            </Form.Item>
          )}
          {mode === 'login' && loginType === 'password' && (
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
              <Checkbox style={{ fontSize: 14 }}>记住我</Checkbox>
              <a href="#" style={{ color: mainColor, fontSize: 14 }}>忘记密码?</a>
            </div>
          )}
          <Form.Item style={{ marginBottom: 0 }}>
            <Button 
              type="primary" 
              htmlType="submit" 
              block 
              size="large" 
              loading={loading}
              style={{ background: mainColor, borderColor: mainColor, borderRadius: 6, fontWeight: 600 }}
            >
              {mode === 'login' ? '登录' : '立即注册'}
            </Button>
          </Form.Item>
        </Form>
        <div style={{ textAlign: 'center', marginTop: 16, fontSize: 14 }}>
          {mode === 'login' ? (
            <>
              还没有账号？ <a style={{ color: mainColor }} onClick={() => handleModeChange('register')}>立即注册</a>
            </>
          ) : (
            <>
              已有账号？ <a style={{ color: mainColor }} onClick={() => handleModeChange('login')}>立即登录</a>
            </>
          )}
        </div>
      </div>
    </Modal>
  );
}
